//
//  DCDCToast.m
//  Demo
//
//  Created by zhaolin on 2023/1/3.
//

#import "DCDCToast.h"

@implementation DCDCToast

+ (void)toastText:(NSString *)string {
    dispatch_async(dispatch_get_main_queue(), ^{
        UIWindow *window = [APPDelegate window];
        [self showTextInSuperView:window Text:string frameType:ToastFrameCenter oneToast:NO userInteractionEnabled:YES];
    });
}

+ (void)showTextInSuperView:(UIView *)superView Text:(NSString *)text frameType:(ToastFrameType)frameType oneToast:(BOOL)onceShow userInteractionEnabled:(BOOL)userInteractionEnabled {
    NSString *toastText = text;
    //null的情况
    if([toastText containsString:@"(Null)"]) {
        toastText =  [toastText stringByReplacingOccurrencesOfString:@"(Null)" withString:@""];
    }
    if([toastText containsString:@"(null)"]) {
        toastText =  [toastText stringByReplacingOccurrencesOfString:@"(null)" withString:@""];
    }
    if([toastText containsString:@"（Null）"]) {
        toastText =  [toastText stringByReplacingOccurrencesOfString:@"（Null）" withString:@""];
    }
    if([toastText containsString:@"（null）"]) {
        toastText =  [toastText stringByReplacingOccurrencesOfString:@"（null）" withString:@""];
    }
    if([toastText containsString:@"null"]) {
        toastText =  [toastText stringByReplacingOccurrencesOfString:@"null" withString:@""];
    }
    if([toastText containsString:@"Null"]) {
        toastText =  [toastText stringByReplacingOccurrencesOfString:@"Null" withString:@""];
    }
    if (!toastText || toastText.length < 1) {
        NSLog(@"tost为空");
        return;
    }
    UIView *bgView = [[UIView alloc] initWithFrame:superView.bounds];
    
    CGFloat viewLaft = 15;
    CGFloat textLaft = 20;
    CGFloat textTop = 10;
    CGFloat bottomSpace = 50;
    
    UIFont *targatFont = kScreenWidth == 320 ? [UIFont systemFontOfSize:14]:[UIFont systemFontOfSize:16];
    CGSize textSize = [self sizeWithText:text font:targatFont maxSize:CGSizeMake(kScreenWidth - (viewLaft + textLaft)*2, MAXFLOAT) LineSpace:5];
    CGFloat viewTagartWidth = textSize.width + textLaft *2 +2;
    CGFloat viewTagartHeight = textSize.height + textTop*2 +2;
    
    UIView *customView = [UIView new];
    customView.layer.shadowOffset = CGSizeMake(3, 3);
    customView.layer.shadowOpacity = 0.8;
    customView.layer.shadowColor = [[UIColor blackColor] colorWithAlphaComponent:0.3].CGColor;
    
//    customView.layer.cornerRadius = viewTagartHeight/2.0;
//    customView.layer.masksToBounds = YES;
    customView.backgroundColor = [APPBlackColor colorWithAlphaComponent:0.85];
    if (frameType==bottomSpace) {
        customView.frame = CGRectMake((kScreenWidth - viewTagartWidth)/2, kScreenHeight - viewTagartHeight - bottomSpace , viewTagartWidth, viewTagartHeight);
    } else {
        customView.frame = CGRectMake((kScreenWidth - viewTagartWidth)/2, (kScreenHeight - viewTagartHeight)/2.0 , viewTagartWidth, viewTagartHeight);
    }

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(textLaft, textTop, textSize.width, textSize.height)];
    label.font = targatFont;
    label.text = toastText;
    label.textAlignment = NSTextAlignmentCenter;
    label.numberOfLines = 0;
    label.textColor = [UIColor whiteColor];
    [customView addSubview:label];
    [bgView addSubview:customView];
    
    
    [superView addSubview:bgView];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [bgView removeFromSuperview];
    });
    
}


// 计算高度的算法
+ (CGSize)sizeWithText:(NSString *)string font:(UIFont *)font maxSize:(CGSize)maxSize LineSpace:(int)lineSpace{
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:lineSpace];//调整行间距
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:string];
    [attStr addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, attStr.length)];
    [attStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, attStr.length)];
    CGSize size = [attStr boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading  context:nil].size;
    
    if ((size.height - font.lineHeight) <= paragraphStyle.lineSpacing) {
        if ([self containChinese:string]) {
            size = CGSizeMake(size.width, size.height-paragraphStyle.lineSpacing);
            NSMutableParagraphStyle *paragraphStylep = [[NSMutableParagraphStyle alloc] init];
            paragraphStylep.lineSpacing = 0;
            [attStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, attStr.length)];
        }
    }
    return size;
}

/**
 TODO: NSString转化为NSMutableAttributedString
 
 @param string 文本
 @param font 文本字体大小
 @param lineSpace 文本行间距
 @return NSMutableAttributedString
 */
+ (NSMutableAttributedString *)stringToAttributedString:(NSString *)string font:(UIFont *)font maxSize:(CGSize)maxSize LineSpace:(int)lineSpace {
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:lineSpace];//调整行间距
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:string];
    [attStr addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, attStr.length)];
    [attStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, attStr.length)];
    CGSize size = [attStr boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading  context:nil].size;
    
    if ((size.height - font.lineHeight) <= paragraphStyle.lineSpacing) {
        if ([self containChinese:string]) {
            size = CGSizeMake(size.width, size.height-paragraphStyle.lineSpacing);
            paragraphStyle.lineSpacing = 0;
            [attStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, attStr.length)];
        }
    }
    return attStr;
}

//判断如果包含中文
+ (BOOL)containChinese:(NSString *)str {
    for(int i=0; i< [str length];i++){ int a = [str characterAtIndex:i];
        if( a > 0x4e00 && a < 0x9fff){
            return YES;
        }
    }
    return NO;
}
@end
